package com.example.beidouapplication;

import static android_serialport_api.hyperlcd.TransformUtils.bytes2HexString;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;


import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;


import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.example.beidouapplication.viewmodel.BdInfoData;
import com.example.beidouapplication.viewmodel.ChuShiZuoBiao;
import com.example.beidouapplication.viewmodel.DaoHangData;
import com.example.beidouapplication.viewmodel.Key;
import com.example.beidouapplication.viewmodel.KeyEvent;
import com.example.beidouapplication.viewmodel.ParaSetData;
import com.example.beidouapplication.viewmodel.SelfTestData;
import com.example.beidouapplication.viewmodel.TimerData;

import java.util.Arrays;

import android_serialport_api.hyperlcd.BaseReader;
import android_serialport_api.hyperlcd.LogInterceptorSerialPort;
import android_serialport_api.hyperlcd.SerialPortManager;
import android_serialport_api.hyperlcd.TransformUtils;

import android.serialport.SerialPort;

public class MainActivity extends Activity implements View.OnClickListener {


    public static final int BAUD = 115200;
    public static final int COM3_BAUD = 38400;
    public static final int COM4_BAUD = BAUD;
    public static final int COM1_BAUD = BAUD;
    public static final int FLAG = 0;
    public static final int COM3_FLAG = 2;

    static void sendKey(int index) {
//    if (Menu.stage != Menu.MENU_INI_S1) {
//        Menu.keyQueue.add(new KeyEvent(Key.Esc, -1));
//    }
        Menu.keyQueue.add(new KeyEvent(Key.ENTER, index));
    }

    static void sendKey(Key type) {
//    if (Menu.stage != Menu.MENU_INI_S1) {
//        Menu.keyQueue.add(new KeyEvent(type, -1));
//    }
        Menu.keyQueue.add(new KeyEvent(type, -1));
    }

    public static SerialPortManager spManager;
    private StringBuffer logTV = null, readTV = null;
    private BaseReader baseReader;
    
    
    // 上位机
    public static String COM1_PORT = "dev/ttyS1"; //这里端口号按照需要测试的改
    // com0 有问题，不能设置校验位


    // 陀螺仪
    public static String COM3_PORT = "dev/ttyS4"; //这里端口号按照需要测试的改

    // 北斗
    public static String COM4_PORT = "dev/ttyCOM0"; //这里端口号按照需要测试的改
    private boolean isAscii = true; //true 时以 ascii 形式发送
    private boolean COM3_isAscii = false; //true 时以 ascii 形式发送
    private boolean COM1_isAscii = true; //true 时以 ascii 形式发送
    private boolean COM4_isAscii = true; //true 时以 ascii 形式发送
    // true时，发送是ascii('123')或者hex，string是ascii(123)，byte是hex(30,31,32)
    // false时，发送是ascii('123')或者hex，string是hex形式的字符('303132')，byte是ascii数组(52,48,52,49,52,50)
// 所以应该用true，然后用byte
    static ChuShiZuoBiao cszb = new ChuShiZuoBiao();
    static DaoHangData daoHangData = new DaoHangData();
    static SelfTestData selfTestData = new SelfTestData();
    static BdInfoData bdInfoData = new BdInfoData();
    static ParaSetData paraSetData = new ParaSetData();
    static TimerData timerData = new TimerData();
    static MainActivity  instance;

    private FragmentQidong fragmentQidong;
    private FragmentDaohang fragmentDaohang;
    private FragmentXunbei fragmentXunbei;
    private FragmentCepiao fragmentCepiao;
    private FragmentMenuIni fragmentMenuIni;


    private Button btnQidong;
    private Button btnDaohang;
    private Button btnXunbei;
    private Button btnCepiao;
    private Button btnXitong;


    private String qd_cspmzb_x;
    private String qd_cspmzb_y;
    private String qd_cspmzb_h;

    private String qd_csddzb_b;
    private String qd_csddzb_l;
    private String qd_csddzb_h;


    Handler handler;
    Runnable runnable;

    /**
     * 用于对Fragment进行管理
     */
    static public FragmentManager fragmentManager;
    static public AlertDialog alertDialog;
    static public AlertDialog alertDialogNoReturn;

    private void initData() {
        spManager = SerialPortManager.getInstances().setLogInterceptor(new LogInterceptorSerialPort() {
            @Override
            public void log(@SerialPortManager.Type final String type, final String port, final boolean isAscii, final String log) {
                String printlog = log;
                Log.d("SerialPortLog", new StringBuffer()
                        .append("串口号：").append(port)
                        .append("\n数据格式：").append(isAscii ? "ascii" : "hexString")
                        .append("\n操作类型：").append(type)
                        .append("操作消息：").append(log).toString());
            }
        });
        baseReader = new BaseReader() {

            @Override
            protected void onParse(final String port, final boolean isAscii, final byte[] read) {
//                byte[] bytes = read.getBytes();
//                char[] chars = read.toCharArray();


//                Log.d("SerialPortRead", new StringBuffer()
//                        .append(port).append("/").append(isAscii ? "ascii" : "hex").append("\n")
//                                .append(" byte: ").append(bytes2HexString(read, read.length)).append("\n")
//                        .toString());

                if (COM1_PORT.equals(port)) {
                    Menu.Buf_Com1.WriteInBufArray(read);
                }
                if (COM3_PORT.equals(port)) {
                    Menu.Buf_Com3.WriteInBufArray(read);
                }
                if (COM4_PORT.equals(port)) {
                    Menu.Buf_Com4.WriteInBufArray(read);
                }
            }
        };
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        // 初始化布局元素
        initViews();

//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);


//        View decorView = getWindow().getDecorView();
//        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
//        decorView.setSystemUiVisibility(uiOptions);

        fragmentManager = getFragmentManager();
        alertDialog = new AlertDialog.Builder(this)
                .setMessage("按任意键返回")
                .setTitle("温馨提示")
                .setCancelable(false)
                .setNegativeButton("返回",
                        (dialog, which) -> {
                            dialog.dismiss();
                            onBackPressed();

                        }
                ).create()
        ;
        alertDialogNoReturn = new AlertDialog.Builder(this)
                .setMessage("按任意键返回")
                .setTitle("温馨提示")
                .setCancelable(false)
                .setNegativeButton("返回",
                        (dialog, which) -> {
                            dialog.dismiss();
                        }
                ).create();

        initData();

//        SerialPort serialPort =  SerialPort.newBuilder(COM1_PORT, BAUD).parity(2).build();

        spManager.startSerialPort(COM1_PORT, COM1_isAscii, COM1_BAUD, baseReader, FLAG);
        spManager.startSerialPort(COM3_PORT, COM3_isAscii, COM3_BAUD, baseReader, COM3_FLAG);
        spManager.startSerialPort(COM4_PORT, COM4_isAscii, COM4_BAUD, baseReader, FLAG);
        
        
        handler = new Handler(Looper.getMainLooper());
        runnable = new Runnable() {
            @Override
            public void run() {
                Menu.main();
                handler.postDelayed(this, 100);
            }
        };

        handler.post(runnable);
        instance = this;

        byte[] zijian = {(byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
//        byte[] canshuchaxun = {(byte) 0xe7, (byte) 0xa7, (byte) 0x08, (byte) 0xdf, (byte) 0x39, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
//        e7a708df39000000

//        spManager.send(COM4_PORT, canshuchaxun);
//            spManager.send(COM4_PORT, new byte[]{(byte) 0xfd, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00, });
//        spManager.send(COM3_PORT, new byte[]{(byte) 0xfd, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00, });
        byte[] cmd = {(byte) 0xf0, (byte) 0x01, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};

        byte[] qidong = {(byte) 0xf2, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06,
                (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};


        byte[] qidongCMD = {(byte) 0xfd, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};


//        byte[] idBit = {(byte) 0xf1, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
        byte[] idBit = {(byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
        byte[] canshuchaxun = {(byte) 0xe4, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
//        spManager.send(COM3_PORT, idBit);
//        spManager.send(COM3_PORT, qidong);
//        spManager.send(COM3_PORT, qidongCMD);
        spManager.send(COM3_PORT, canshuchaxun);
//        canshuchaxun = new byte[]{(byte) 0xe4, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
//        spManager.send(COM3_PORT, canshuchaxun);
//
//        canshuchaxun = new byte[]{(byte) 0xe4, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
//        spManager.send(COM3_PORT, canshuchaxun);

//        spManager.send(COM1_PORT, qidong);
//        spManager.send(COM1_PORT, qidongCMD);
        // 第一次启动时选中第0个tab
//        setTabSelection(0);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        boolean debug = true;
        if (!debug && Menu.noBackStage.contains(Menu.stage)) {
            return;
        }
        Menu.keyQueue.add(new KeyEvent(Key.Esc, -1));
    }

    static void alertAndReturn(String msg) {
        alertDialog.setMessage(msg);
        alertDialog.show();
    }

    static void alertNoReturn(String msg) {
        alertDialogNoReturn.setMessage(msg);
        alertDialogNoReturn.show();
    }

    /**
     * 在这里获取到每个需要用到的控件的实例，并给它们设置好必要的点击事件。
     */
    private void initViews() {
        btnQidong = findViewById(R.id.button_first);
        btnDaohang = findViewById(R.id.button_first2);
        btnXunbei = findViewById(R.id.button_first3);
        btnCepiao = findViewById(R.id.button_first4);
        btnXitong = findViewById(R.id.button_first5);


        btnQidong.setOnClickListener(this);
        btnDaohang.setOnClickListener(this);
        btnXunbei.setOnClickListener(this);
        btnCepiao.setOnClickListener(this);
        btnXitong.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_first) {
            setTabSelection(0);
//            btnQidong.setTextColor(getResources().getColor(R.color.red));
        } else if (v.getId() == R.id.button_first2) {
            setTabSelection(1);
//            btnDaohang.setTextColor(getResources().getColor(R.color.red));
        } else if (v.getId() == R.id.button_first3) {
            setTabSelection(2);
//            btnXunbei.setTextColor(getResources().getColor(R.color.red));
        } else if (v.getId() == R.id.button_first4) {
            setTabSelection(3);
        } else if (v.getId() == R.id.button_first5) {
            setTabSelection(4);
//            btnXitong.setTextColor(getResources().getColor(R.color.red));
        }

    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
     */
    public void setRed(int index       ){
    clearSelection();
        switch (index) {
        case 0:
            btnQidong.setTextColor(getResources().getColor(R.color.red));
            break;
        case 1:
            btnDaohang.setTextColor(getResources().getColor(R.color.red));

            break;
        case 2:
            btnXunbei.setTextColor(getResources().getColor(R.color.red));
            break;
        case 3:
            btnCepiao.setTextColor(getResources().getColor(R.color.red));
            break;
        case 4:
            btnXitong.setTextColor(getResources().getColor(R.color.red));
            break;
        default:
            break;
    }
    }
    private void setTabSelection(int index) {

        if (Menu.stage != Menu.MENU_MAIN_S1) {
            return;
        }
        // 每次选中之前先清楚掉上次的选中状态
        clearSelection();
        // 开启一个Fragment事务
//        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
//        hideFragments(transaction);
        switch (index) {
            case 0:
                btnQidong.setTextColor(getResources().getColor(R.color.red));
                break;
            case 1:
                btnDaohang.setTextColor(getResources().getColor(R.color.red));

                break;
            case 2:
                btnXunbei.setTextColor(getResources().getColor(R.color.red));
                break;
            case 3:
                btnCepiao.setTextColor(getResources().getColor(R.color.red));
                break;
            case 4:
                btnXitong.setTextColor(getResources().getColor(R.color.red));
                break;
            default:
                break;
        }
//        transaction.commit();

        Menu.stage = Menu.MENU_MAIN_S1;
        Menu.keyQueue.add(new KeyEvent(Key.ENTER, index));
    }

    /**
     * 清除掉所有的选中状态。
     */
    public void clearSelection() {
//        messageImage.setImageResource(R.drawable.message_unselected);
//        messageText.setTextColor(Color.parseColor("#82858b"));
//        contactsImage.setImageResource(R.drawable.contacts_unselected);
//        contactsText.setTextColor(Color.parseColor("#82858b"));
//        newsImage.setImageResource(R.drawable.news_unselected);
//        newsText.setTextColor(Color.parseColor("#82858b"));
//        settingImage.setImageResource(R.drawable.setting_unselected);
//        settingText.setTextColor(Color.parseColor("#82858b"));
        btnQidong.setTextColor(getResources().getColor(R.color.black));
        btnDaohang.setTextColor(getResources().getColor(R.color.black));
        btnXunbei.setTextColor(getResources().getColor(R.color.black));
        btnCepiao.setTextColor(getResources().getColor(R.color.black));
        btnXitong.setTextColor(getResources().getColor(R.color.black));

    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (fragmentQidong != null) {
            transaction.hide(fragmentQidong);
        }
        if (fragmentDaohang != null) {
            transaction.hide(fragmentDaohang);
        }
        if (fragmentXunbei != null) {
            transaction.hide(fragmentXunbei);
        }
        if (fragmentCepiao != null) {
            transaction.hide(fragmentCepiao);
        }
        if (fragmentMenuIni != null) {
            transaction.hide(fragmentMenuIni);
        }
//            transaction.hide(FragmentQidongShuRuZuoBiaoQueRen.instance);
//            transaction.hide(FragmentQidongShuRuZuoBiao.instance);
    }
}